/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package me.joshua.tools4j.web;

import me.joshua.tools4j.dal.ActionRecordRepository;
import me.joshua.tools4j.dal.UserRepository;
import me.joshua.tools4j.model.Action;
import me.joshua.tools4j.model.ActionRecord;
import me.joshua.tools4j.service.MailService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * 
 * @author Joshua
 */
// @Controller
public class Action2Controller {

	private static final Logger		LOGGER	= LoggerFactory.getLogger(Action2Controller.class);

	@Autowired
	private ActionRecordRepository	actionRecordRepository;
	@Autowired
	private UserRepository			userRepository;
	@Autowired
	private MailService				mailService;

	@RequestMapping(value = "/n/{name}", method = RequestMethod.GET)
	public String greeting(@PathVariable String name, Model model) {
		LOGGER.info(String.format("Name2 is %s", name));
		model.addAttribute("name", name);
		return "/hello";
	}

	@RequestMapping(value = "/mail/{name}", method = RequestMethod.GET)
	public String mail(@PathVariable String name, Model model) {

		SimpleMailMessage mailMessage = new SimpleMailMessage();
		mailMessage.setTo("daonan.zhan@gmail.com");
		mailMessage.setSubject("Greeting");
		mailMessage.setFrom("zdn880729@gmail.com");
		mailMessage.setText(String.format("Hello %s.\nThanks\nRegards\nJoshua", name));
		mailService.send(mailMessage);

		model.addAttribute("name", name);
		return "/hello";
	}

	@RequestMapping(value = "/action/{id}", method = RequestMethod.GET)
	public String show(@PathVariable("id") Action action, Model model) {
		model.addAttribute("action", action);
		return "/action";
	}

	@RequestMapping(value = "/m/{id}", method = RequestMethod.GET)
	public String modify(@PathVariable("id") ActionRecord record, Model model) {

		record.setCost(Long.toString(System.currentTimeMillis()));
		actionRecordRepository.save(record);
		model.addAttribute("record", record);
		System.out.println(userRepository.findByUsername(record.getLastModifiedBy().getUsername()));
		return "/record";
	}

	@RequestMapping(value = "/m/{id}", method = RequestMethod.GET)
	public String edit(@PathVariable("id") Action record, Model model) {

		return "/action_edit";
	}
}
